<template>
    <div>
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>宿舍管理</el-breadcrumb-item>
        <el-breadcrumb-item>宿舍列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图区 -->
      <el-card>

        <!-- 搜索与添加区域 -->
        <el-row :gutter= "20">
          <el-col :span="9">
            <el-input placeholder="请输入寝室号" v-model="queryInfo.query" class="input-with-select" clearable @clear="getDormitoryListLimit" >
              <el-select placeholder="请选择楼栋号" v-model="queryInfo.select" slot="prepend" clearable @clear="getDormitoryListLimit" >
                <el-option
                  v-for="item in buildings"
                  :key="item.buildingId"
                  :label="item.buildingNumber"
                  :value="item.buildingId">
                </el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search" @click="getDormitoryListLimit"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加宿舍</el-button>
          </el-col>
        </el-row>

        <!-- 宿舍列表主体区域 -->
        <el-table :data="dormitoryList" border stripe  >
          <!-- 展开列 寝室所入住的学生 -->
          <el-table-column type="expand">
            <template slot-scope="scope"><!--v-if="handle(scope.row.studentList[0].stuName)"-->
             <el-table :data="scope.row.studentList"  border >
                   <el-table-column align="center" type="index" label="#"></el-table-column>
                   <el-table-column align="center" prop="userName" label="学号"></el-table-column>
                   <el-table-column align="center" prop="stuName" label="姓名"></el-table-column>
                   <el-table-column align="center" prop="stuIndate" label="入住时间"></el-table-column>
                   <el-table-column align="center" prop="stuClass.className" label="所在班级"></el-table-column>
                   <el-table-column align="center" prop="stuBed" label="床铺号"></el-table-column>
             </el-table>
            </template>
          </el-table-column>
          <el-table-column align="center" type="index" label="#"></el-table-column>
          <el-table-column align="center" prop="building.buildingNumber" label="楼栋号"></el-table-column>
          <el-table-column align="center" label="楼栋类型">
            <template slot-scope="scope">
              <div v-if="scope.row.building.buildingType === 1">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nan"></use>
                </svg>
              </div>
              <div v-else>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nv"></use>
                </svg>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dormitoryRoom" label="寝室号"></el-table-column>
          <el-table-column align="center" label="卫生分数">
            <template slot-scope="scope">
              {{scope.row.dormitoryScore == null ? "/" : scope.row.dormitoryScore}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="宿舍长">
            <template slot-scope="scope">
              {{scope.row.dormitoryHeadOfTheDormitory == null ? "/" : scope.row.dormitoryHeadOfTheDormitory}}
            </template>
          </el-table-column>
          <el-table-column align="center"  label="已住人数">
            <template slot-scope="scope">
              {{scope.row.dormitoryLiveIn == null ? 0 : scope.row.dormitoryLiveIn}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dormitorySpendable" label="可住人数"></el-table-column>
          <el-table-column align="center" label="操作" width="140px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.buildingId, scope.row.dormitoryRoom)" ></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDormitory(scope.row.dormitoryId)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <!-- 添加宿舍对话框 -->
        <el-dialog
        title="添加宿舍"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <!-- 内容主体区 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item label="楼栋号" prop="buildingId">
             <el-select placeholder="请选择" v-model="addForm.buildingId">
               <el-option
                v-for="item in buildings"
                :key="item.buildingId"
                :label="item.buildingNumber"
                :value="item.buildingId">
               </el-option>
             </el-select>
            </el-form-item>
            <el-form-item label="寝室号" prop="dormitoryRoom">
              <el-input v-model="addForm.dormitoryRoom" ></el-input>
            </el-form-item>
            <el-form-item label="可住人数" prop="dormitorySpendable">
              <el-select placeholder="请选择" v-model="addForm.dormitorySpendable">
                <el-option
                  v-for="item in spendableList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false" >取 消</el-button>
            <el-button type="primary" @click="addDormitory">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 编辑楼栋寝室信息的对话框 -->
        <el-dialog
          title="修改寝室信息"
          :visible.sync="editDialogVisible"
          width="50%">
          <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
            <el-form-item label="寝室号" prop="dormitoryRoom">
              <el-input v-model="editForm.dormitoryRoom" disabled></el-input>
            </el-form-item>
            <el-form-item label="卫生分数" prop="dormitoryScope">
              <el-select placeholder="请选择" v-model="editForm.dormitoryScore">
                <el-option
                  v-for="item in dormitoryScopeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="寝室长" prop="dormitoryScope">
              <el-select placeholder="请选择" v-model="editForm.dormitoryHeadOfTheDormitory">
                <el-option label="暂无" value="-1"/>
                <el-option
                  v-for="item in this.editForm.studentList"
                  :key="item.userName"
                  :label="item.stuName"
                  :value="item.stuName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="可住人数" prop="dormitoryScope">
              <el-select placeholder="请选择" v-model="editForm.dormitorySpendable">
                <el-option
                  v-for="item in spendableList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDormitory">确 定</el-button>
        </span>
        </el-dialog>

      </el-card>

    </div>
</template>

<script>
    export default {
        data() {
          return {
            /* 获取宿舍列表的参数对象 */
            queryInfo: {
              select: '',
              query: '',
              //当前的页数
              pageNum: 1,
              //当前每页显示多少条数据
              pageSize: 10
            },
            /* 总记录数 */
            total: 0,
            /* 楼栋列表 */
            buildings: [],
            /* 寝室可住人数列表 */
            spendableList: [
              {
                value: 4,
                label: '四人寝'
              },
              {
                value: 6,
                label: '六人寝'
              },
              {
                value: 8,
                label: '八人寝'
              },
            ],
            /* 宿舍列表 */
            dormitoryList: [],
            /* 控制添加寝室的对话框的显示/隐藏 */
            addDialogVisible: false,
            /* 控制编辑寝室的对话框的显示/隐藏 */
            editDialogVisible: false,
            /* 添加宿舍的表单数据 */
            addForm: {
              buildingId: '',
              dormitoryRoom: '',
              dormitorySpendable: ''
            },
            /* 编辑宿舍的表单数据 */
            editForm: {
              buildingId: '',
              dormitoryId: '',
              dormitoryRoom: '',
              dormitoryScore: null,
              dormitoryHeadOfTheDormitory: '',
              dormitoryLiveIn: '',
              dormitorySpendable: '',
              // 寝室学生列表 //
              studentList: [],
            },
            /* 添加表单的验证规则 */
            addFormRules: {
                buildingId: [
                  {required: true, message: '请选择楼栋', trigger: 'blur'}
                ],
              dormitoryRoom: [
                {required: true, message: '输入寝室号', trigger: 'blur', },
              ],
              dormitorySpendable: [
                {required: true, message: '请选择可住人数', trigger: 'blur'}
              ]
            },
            /* 编辑表单的验证规则 */
            editFormRules: {},



          /* 卫生分数json数据 */
            dormitoryScopeList: [
              {
                value: null,
                label: '未检查'
              },
              {
                value: 0,
                label: '0'
              },
              {
                value: 1,
                label: '1'
              },
              {
                value: 2,
                label: '2'
              },
              {
                value: 3,
                label: '3'
              },
              {
                value: 4,
                label: '4'
              },
              {
                value: 5,
                label: '5'
              },
              {
                value: 6,
                label: '6'
              },
              {
                value: 7,
                label: '7'
              },
              {
                value: 8,
                label: '8'
              },
              {
                value: 9,
                label: '9'
              },
              {
                value: 10,
                label: '10'
              },
            ]

          }
        },

      /* 生命周期函数 */
      created() {
        this.getBuildingList();
        this.getDormitoryListLimit();
      },

      methods: {

          /* 添加对话框打开前，渲染出 楼栋列表*/
          getBuildingList() {
            //发送请求 获取楼栋列表信息
            this.$axios.get(this.$http+'/buildingManageController/getBuildingIdList').then(res => {
              this.buildings = res.data.datas.buildingList;
            }).catch(err => {
              this.$message.error("楼栋列表请求失败");
              console.log(err)
            });
          },

        /* 根据 楼栋号 寝室号 查询  可无*/
        async getDormitoryListLimit(){
          await this.$axios.get(this.$http+'/dormitoryManageController/getDormitoryListLimit', {
            params: this.queryInfo
          }).then(res => {
            console.log(res)
            this.dormitoryList = res.data.datas.dormitoryList;
            this.total = res.data.datas.total;
          }).catch(err => {
            console.log(err)
          })
        },

          /* 添加新的寝室 */
          addDormitory() {
            //进行表单验证
            this.$refs.addFormRef.validate(valid => {
              //如果valid为false，则不进行数据提交
              if (!valid) return;

              //访问后台，判断该楼栋该寝室号是否存在
              this.$axios.get(this.$http+'/dormitoryManageController/checkRoomByBuildingNumber',
                {
                  params: {
                    buildingId: this.addForm.buildingId,
                    dormitoryRoom: this.addForm.dormitoryRoom
                  }
                }
              ).then(res => {
                // 如果已录入，则弹出提示框
                if (res.data.code === 100)
                  return this.$message.warning("该楼栋的"+this.addForm.dormitoryRoom+"宿舍已录入")
                //数据无误，发送添加请求
                this.$axios.post(this.$http+'/dormitoryManageController/addDormitory', this.addForm).then(res => {
                  if (res.data.code === 200)
                    this.$message.success("添加成功!");
                  else if (res.data.code === 100)
                    this.$message.warning("服务器繁忙");
                });
                //隐藏添加对话框
                this.addDialogVisible = false;

                //刷新列表
                this.getDormitoryListLimit();

              }).catch(err => {
                console.log(err);
                this.$message.error("异常错误,请联系系统管理员")
              })

            })
          },

        /* 展示编辑寝室的对话框 */
        async showEditDialog(buildingId, dormitoryRoom) {
          console.log(buildingId, dormitoryRoom)
          // 发送网络请求， 获取当前寝室信息
          await this.$axios.get(this.$http+'/dormitoryManageController/getDormitoryInfo?buildingId='+buildingId+'&dormitoryRoom='+dormitoryRoom).then(res => {
           this.editForm = res.data.datas.dormitoryInfo;
           const tmp = res.data.datas.dormitoryInfo.dormitoryHeadOfTheDormitory;
           this.editForm.dormitoryHeadOfTheDormitory = tmp === null ? '-1' : tmp;
          }).catch(err => {
            console.log(err)
            this.$message.error("系统异常，请联系系统管理员")
          });
          //显示编辑对话框
          this.editDialogVisible = true
        },

        /* 提交需要编辑的表单数据 */
        async editDormitory() {
          //对寝室可住人数小于已住人数的错误进行处理
          if (this.editForm.dormitorySpendable < this.editForm.dormitoryLiveIn)
            return this.$message.error("当前宿舍已住" + this.editForm.dormitoryLiveIn + "人,不能修改成" + this.editForm.dormitorySpendable + "人寝")
          // -1表示还未检查
          this.editForm.dormitoryHeadOfTheDormitory = this.editForm.dormitoryHeadOfTheDormitory === '-1' ? null : this.editForm.dormitoryHeadOfTheDormitory;
          console.log(this.editForm)
         //发送网络请求，修改寝室信息数据
          await this.$axios.put(this.$http+'/dormitoryManageController/editDormitory', this.editForm).then(res => {
            if (res.data.code === 200)
              this.$message.success("修改宿舍信息成功！");
            else if (res.data.code === 100)
              this.$message.error("修改宿舍信息失败！");
            //隐藏添加用户对话框
            this.editDialogVisible = false;
            //刷新列表
            this.getDormitoryListLimit();
          }).catch(err => {
            console.log(err)
          });
        },

        /* 监听 pageNum 改变的事件 */
        handleCurrentChange(newPage) {
          this.queryInfo.pageNum = newPage ;
          //每次改变之后，重新获取数据
          this.getDormitoryListLimit();
        },

          /* 监听 pageSize 改变的事件 */
          handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            //每次改变之后，重新获取数据
            this.getDormitoryListLimit();
          },

          /* 删除寝室 */
          async deleteDormitory(dormitoryId) {
            //确定是否删除
            const confirmResult = await this.$confirm('此操作将删除该寝室，是否继续?', '提示',{
              confirmButtonText: '我要删除',
              cancelButtonText: '按错了',
              type: 'warning'
            }).catch(err => err)
            if (confirmResult !== 'confirm')
              return this.$message.info('已取消删除')
            else {
              //发送网络请求，确定删除
              await this.$axios.delete(this.$http+'/dormitoryManageController/deleteDormitory?dormitoryId='+dormitoryId).then(res => {
                if (res.data.code === 200)
                  this.$message.success("删除宿舍成功！");
                else if (res.data.code === 100)
                  this.$message.error("删除宿舍失败！");
                //刷新宿管列表
                this.getDormitoryListLimit();
              }).catch(err => {
                console.log(err)
              })
            }
          },

          /* 监听添加对话框的关闭， 对其内容进去清空 */
          addDialogClosed() {
            this.$refs.addFormRef.resetFields();
          },

        /* 对宿舍还无人员居住的就不显示 */
        handle(stuName) {
            if (stuName === null)
              return false;
            return true;
        }

      }
    }
</script>

<style scoped lang="less">

</style>
